//
//  WCNLoginVC.m
//  WCN
//
//  Created by 杨鑫 on 15/5/29.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNLoginVC.h"
#import "WCNTabBarVC.h"
//VC
#import "WCNForgotPwdVC.h"
//
#import "NSString+Utilities.h"
//
#import "WCDefaultManager.h"
#import "WCPopupLayerManager.h"
#import "WCNetworkAccessManager.h"
#import "Macros.h"
#import "WCNNewsDetailVC.h"
#import "WCBaiduPushBindHelp.h"
#import "WSJTexfildForSuggestionList.h"
#import "WCBorderView.h"
#import "Constants.h"
#import "WCNAppDelegate.h"

@interface WCNLoginVC () <UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet WCBorderView *phoneBgView;

@property (weak, nonatomic) IBOutlet WSJTexfildForSuggestionList *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *pwdTextField;

@end

@implementation WCNLoginVC

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.title = @"登录";
        
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.phoneTextField.text = [[WCDefaultManager shareMg] lastAccount];
    self.phoneTextField.delegate = self;
  
}


- (void)showSuggestList{
    if ([[WCDefaultManager shareMg]getPhoneAccouts].count>0 ) {
        self.phoneTextField.ableSuggestinglist = YES;
        self.phoneTextField.superView = self.view;
        CGRect  frame = self.phoneBgView.frame;
        self.phoneTextField.customFrame = CGRectMake(frame.origin.x, CGRectGetMaxY(frame), kScreenWidth -50 , 100);
        self.phoneTextField.suggestionArray =[[WCDefaultManager shareMg]getPhoneAccouts];
        weakSelf_define;
        self.phoneTextField.callBack = ^(NSString *phone){
            weakSelf.phoneTextField.text =phone;
        };
    }


}
#pragma mark - Nib Targets
//click backgroundView
- (IBAction)bgTouchDown:(id)sender
{
    
    [self.phoneTextField hideList];
    [self.view endEditing:YES];
}

- (IBAction)regNotAction:(id)sender {
    WCNNewsDetailVC *vc =[[WCNNewsDetailVC alloc] init];
    vc.url =[NSURL URLWithString:kRegNotUrl];
    vc.title =@"护礼家-医护版";
    [self.navigationController pushViewController:vc animated:YES];
}
//密码框  是否安全显示
- (IBAction)togglePwdBtn:(UIButton *)sender
{
    
    //http://stackoverflow.com/questions/7305538/uitextfield-with-secure-entry-always-getting-cleared-before-editing
    
    BOOL shouldBecomeFirstResponder = self.pwdTextField.isFirstResponder?YES:NO;
    BOOL selected = sender.selected;
    
    [sender setSelected:!selected];
    self.pwdTextField.enabled = NO;
    self.pwdTextField.secureTextEntry = selected;
    self.pwdTextField.enabled = YES;
    
    if (shouldBecomeFirstResponder) {
        [self.pwdTextField becomeFirstResponder];
    }
}

//忘记密码
- (IBAction)showPwdVC:(id)sender {
    WCNForgotPwdVC *pwdVC = [[WCNForgotPwdVC alloc] init];
    [self.navigationController pushViewController:pwdVC animated:YES];
}

// 点击登录
- (IBAction)doLogin:(id)sender {
    
    
    [self.phoneTextField hideList];
    //verify
    NSString *account = self.phoneTextField.text, *password = self.pwdTextField.text;
    
    
    if ([account isEmpty] || [password isEmpty]) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"用户名或密码不能为空" withView:self.view];
        return;
    }
    
    if ([password hasSpace]) {
        [[WCPopupLayerManager shareMg] showTextOnly:@"密码不能有空格" withView:self.view];
        return;
    }
    
    weakSelf_define;
    if ([account isMobile]) {
        MBProgressHUD *hud = [[WCPopupLayerManager shareMg] showSimple:[UIApplication sharedApplication].keyWindow];
        [[WCNetworkAccessManager sharedMg] POST:kLoginUrl
                                     parameters:@{@"mobileNo": account, @"password":[password md5String]}
                                        success:^(NSDictionary *responseData){
                                            NSDictionary *dictData =responseData[@"data"];
                                            
                                            NSDictionary *userData =dictData[@"sessionUser"];
                                            
                                            NSMutableDictionary *dataDict =[NSMutableDictionary new];
                                            dataDict[@"hospitalName"] =userData[@"hospitalName"];
                                            
                                            dataDict[@"sessionKey"] =dictData[@"sessionKey"];
                                            //添加另一个字典的所有条目（key－value）
                                            [dataDict addEntriesFromDictionary:userData[@"value"]];
                                            dataDict[@"pwd"] =[password md5String];
                                            NSLog(@"----%@",dataDict);
                                            
                                            
                                            [[WCDefaultManager shareMg] login:dataDict];
                                            [[WCDefaultManager shareMg] saveLastAccouts:account name:dataDict[@"name"]];
                                            //绑定channelID
                                            [WCBaiduPushBindHelp bindToService];
                                            WCNAppDelegate *delegate = (WCNAppDelegate *)[UIApplication sharedApplication].delegate;
                                            if (delegate.isFromDevtip == YES) {
                                                [[NSNotificationCenter defaultCenter] postNotificationName:UserLoginFromDevtipNotification object:nil userInfo:nil];
                                            }else {
                                                
                                                [[NSNotificationCenter defaultCenter] postNotificationName:UserLoginNotification object:nil userInfo:nil];
                                                WCNTabBarVC *mainVC = [[WCNTabBarVC alloc] init];
                                                [weakSelf.navigationController setViewControllers:@[mainVC] animated:YES];
                                            }
                                           
                                        } failure:nil netError:nil always:^{
                                            [hud hide:YES];
                                        }];
    } else {
        [[WCPopupLayerManager shareMg] showTextOnly:@"手机号错误" withView:self.view];
        return;
    }
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    if (textField.tag == 0) {
        self.pwdTextField.text = @"";
    }
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField.tag == 1) {
        [textField resignFirstResponder];
        [self doLogin:nil];
        return YES;
    }
    
    return NO;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    if (textField.tag ==0) {
        [self showSuggestList];
    }
}
@end
